package com.tanhua.app.controllerservice;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.db.QuestionApi;
import com.tanhua.api.db.UserInfoApi;
import com.tanhua.api.mongo.FriendsApi;
import com.tanhua.api.mongo.RecommendUserApi;
import com.tanhua.api.mongo.TanHuaApi;
import com.tanhua.api.mongo.UserLikeApi;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageBeanVo;
import com.tanhua.domain.vo.TanhuaVo;
import com.tanhua.domain.vo.TodayBest;
import com.tanhua.domain.vo.UserHolder;
import com.tanhua.template.HuanXinTemplate;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TanHuaService {


    @Reference
    private RecommendUserApi recommendUserApi;

    @Reference
    private UserLikeApi userLikeApi;

    @Reference
    private FriendsApi friendsApi;

    @Reference
    private TanHuaApi tanHuaApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;


    public ResponseEntity todayBest() {

        // 1 根据当前登录用户的id查询缘分值最高的女神id （mongoDB）
        RecommendUser recommendUser =recommendUserApi.findBytodayBest(UserHolder.getUser().getId());
        //2 根据女神的id去userInfo表中查询女神的信息  (mysql)
        UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());
        //模拟数据 没有缘分人都是2号
        if(recommendUser==null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(2L); //在这里是写死的  你可以做成随机的
            recommendUser.setScore(99.0); //这里的得分也是写死的
        }

        //3 将女生信息和缘分值封装到vo中
        TodayBest todayBest = new TodayBest();
        todayBest.setFateValue(recommendUser.getScore().longValue());
        BeanUtil.copyProperties(userInfo,todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity recommendation(Integer page, Integer pagesize) {

        //1 分页查询女神的id和缘分值
        PageBeanVo pageBean= recommendUserApi.findRecommendation(page,pagesize,UserHolder.getUser().getId());
        List<RecommendUser> items = (List<RecommendUser>) pageBean.getItems();

        // 没有佳人（假数据）
        if(items.size()==0){
            items=fromtuijianren();
        }


        List<TodayBest> list=new ArrayList<TodayBest>();
        //有佳人
        if(CollectionUtil.isNotEmpty(items)){
            //2 根据女神id查询女神信息
            for (RecommendUser recommendUser : items) {
                boolean flg = friendsApi.isFriends( recommendUser.getUserId().intValue(),UserHolder.getUser().getId());
                boolean boo = userLikeApi.isLove(UserHolder.getUser().getId(),recommendUser.getUserId());

                if (!flg&&!boo) {
                    UserInfo userInfo = userInfoApi.findUserInfo(recommendUser.getUserId());

                    //3 将女神信息和缘分值封装给vo
                    TodayBest todayBest = new TodayBest();
                    BeanUtil.copyProperties(userInfo,todayBest);
                    todayBest.setTags(userInfo.getTags().split(","));

                    todayBest.setFateValue(recommendUser.getScore().longValue());

                    list.add(todayBest);
                }

            }
        }

        //4 将vo数据给pageBean
        pageBean.setItems(list);

        //5 返回pageBean
        return ResponseEntity.ok(pageBean);
    }



    private List<RecommendUser> fromtuijianren() {
        List<RecommendUser> list=new ArrayList<RecommendUser>();

        for(Long i=1l;i<=10;i++){
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i);
            recommendUser.setScore(RandomUtils.nextDouble(60,99));
            list.add(recommendUser);
        }
        return list;
    }

    public ResponseEntity personalInfo(Integer jrid) {

        //根据佳人id查询佳人的信息
        UserInfo userInfo = userInfoApi.findUserInfo(jrid.longValue());
        //根据佳人id和当前登录用户查询2者之间的缘分值 recommend_user
        RecommendUser user=recommendUserApi.findScore(jrid,UserHolder.getUser().getId());
        if(user==null){
            user=new RecommendUser();
            user.setScore(99d); //假收据
        }
        // 封装佳人信息和当前登录用户之间的缘分值 给app
        TodayBest todayBest = new TodayBest();
        BeanUtil.copyProperties(userInfo,todayBest);
        todayBest.setTags(userInfo.getTags().split(","));
        todayBest.setFateValue(user.getScore().longValue());

        return ResponseEntity.ok(todayBest);
    }

    public ResponseEntity strangerQuestions(Integer userId) {

        //带着userId查询问题表
        Question question = questionApi.findQuestion(userId.longValue());

        if(question==null){
            question=new Question();
            question.setStrangerQuestion("你是GG还是MM？");
        }

        return ResponseEntity.ok(question.getStrangerQuestion());

    }

    public ResponseEntity toStrangerQuestions(Integer userId, String info) {

        //当前登录用户
        UserInfo userInfo = userInfoApi.findUserInfo(UserHolder.getUser().getId());

        //拼装环信要的数据
        Map<String,String> hxMap=new HashMap<>(); //bug: 环信要求的key value都是String
        hxMap.put("userId",userInfo.getId().toString());
        hxMap.put("nickname",userInfo.getNickname());
        //根据佳人的id获取佳人的问题
        Question question = questionApi.findQuestion(userId.longValue());
        hxMap.put("strangerQuestion",question.getStrangerQuestion());
        hxMap.put("reply",info);

        //map转换成json数据给环信
        String json = JSON.toJSONString(hxMap);
        //调用环信方法发送验证消息
        huanXinTemplate.sendMsg(userId.toString(),json);


        return ResponseEntity.ok(null);
    }

    public ResponseEntity findCards() {

        Long userId = UserHolder.getUser().getId();
        List<RecommendUser> lists = tanHuaApi.findCard(userId);

        List<TanhuaVo> userInfoList = new ArrayList<>();
        if (lists.size()>0){
            for (RecommendUser recommendUser : lists) {

                Long recommendUserId = recommendUser.getUserId();
                UserInfo userInfo = userInfoApi.findUserInfo(recommendUserId);
                TanhuaVo tanhuaVo = new TanhuaVo();
                BeanUtil.copyProperties(userInfo,tanhuaVo);
                tanhuaVo.setTags(userInfo.getTags().split(","));
                tanhuaVo.setId(userInfo.getId().intValue());
                boolean flg = friendsApi.isFriends(recommendUserId.intValue(),userId);
                boolean boo = userLikeApi.isLove(userId,recommendUserId);
                if (!flg&&!boo){
                    userInfoList.add(tanhuaVo);
                }

            }
        }
        Object[] objects = userInfoList.toArray();

        return ResponseEntity.ok(objects);



    }

    public ResponseEntity tanhuaLove(String uid) {

        Long userId = UserHolder.getUser().getId();

        userLikeApi.save(Long.parseLong(uid),userId);

        boolean flg = userLikeApi.isFan(userId, Long.parseLong(uid));
        if (flg){
            registerHuanxinUser(Long.parseLong(uid),userId);//把普通用户注册为环信用户
            friendsApi.contacts(userId.intValue(),Long.parseLong(uid));
            userLikeApi.deleteUserLike(Long.parseLong(uid),userId.intValue());
            huanXinTemplate.addContacts(userId,Long.parseLong(uid));
        }

        return ResponseEntity.ok(null);
    }

    public ResponseEntity tanhuaUnLove(String uid) {

        Long userId = UserHolder.getUser().getId();
        tanHuaApi.tanhuaUnlove(Long.parseLong(uid),userId);
        return ResponseEntity.ok(null);
    }

    public void registerHuanxinUser(Long uid,Long userId){

        int huanXinUid = huanXinTemplate.getHuanXinUser(uid);
        if (huanXinUid==404){
            huanXinTemplate.register(uid);
        }
        int huanXinUserId = huanXinTemplate.getHuanXinUser(userId);
        if (huanXinUserId==404){
            huanXinTemplate.register(userId);
        }
    }

}
